import datetime

from fastapi import APIRouter

from apps.core.global_model import SaveJournalIdModel
from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import InputInfoModel, ReturnInfo, SUCCESS
from apps.sql_app.mmongodb import Coll

router = APIRouter(route_class=ContextIncludedRoute)


@router.post("/step1/update_patent")
async def journal_list(input: InputInfoModel[dict]):
    """

    :param input:
    :return:
    """
    return_info = ReturnInfo()
    ftp_patent_raw = Coll.get_ftp_patent_raw()
    ftp_patent_his = Coll.get_ftp_patent_his()
    save_dicts = input.data
    save_dicts["_id"] = save_dicts["pid"]

    save_dicts = {k.lower(): v for k, v in save_dicts.items()}

    pid = save_dicts["pid"]
    cjip = await ftp_patent_raw.find_one({"_id": pid})
    if cjip:
        cjip["_id"] = pid + "_" + str(datetime.datetime.now())
        result = await ftp_patent_his.insert_one(cjip)
        save_dicts["update_time"] = str(datetime.datetime.now())
        save_dicts["create_time"] = cjip["create_time"]
        result = await ftp_patent_raw.replace_one({'_id': pid}, save_dicts)
    else:
        save_dicts["update_time"] = str(datetime.datetime.now())
        save_dicts["create_time"] = str(datetime.datetime.now())
        result = await ftp_patent_raw.insert_one(save_dicts)

    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "保存到mongodb成功"
    return_info.data = ""
    return return_info.todict()
